//
//  TQQTyperwriteLabel.swift
//  SwiftLearning
//
//  Created by 黄龙 on 2024/1/30.
//

import UIKit
import AudioToolbox

class TQQTyperwriteLabel: UILabel {
    var typewriteTimeInterval:CGFloat = 0.3
    var playSound:Bool = false
    var typer_soundid:SystemSoundID = 0 //import AudioToolbox
    var typer_color:UIColor?
    var timer:Timer?
    var currentIndex:Int = 0
    var complete_block:os_block_t?
    
    deinit{
        typer_soundid = 0
        AudioServicesPlaySystemSound(0)
        stopTimer()
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        if let url = Bundle.main.url(forResource: "typewriter", withExtension: "wav"){
            AudioServicesCreateSystemSoundID(url as CFURL, &typer_soundid)
        }
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    func startTyperwrite()
    {
        if typer_color == nil{
            typer_color = .label
        }
    
        timer = Timer.scheduledTimer(withTimeInterval: typewriteTimeInterval, repeats: true) { [weak self]_ in
            self?.outPutWord()
        }
        if let timer = timer{
            RunLoop.main.add(timer, forMode: .common)
            timer.fire()
        }
        
    }
    
    func stopTimer(){
        if let timer = self.timer{
            timer.invalidate()
            self.timer = nil
        }
    }
    
    func outPutWord()
    {
        if let title = self.text {
            if title.count == self.currentIndex{
                stopTimer()
                self.complete_block?()
            }else{
                self.currentIndex += 1
                let mutableAttributedString:NSMutableAttributedString = NSMutableAttributedString(string: title)
                mutableAttributedString.addAttribute(.foregroundColor, value: self.typer_color as Any, range: NSMakeRange(0, self.currentIndex))
                self.attributedText = mutableAttributedString
                self.playSound ? AudioServicesPlaySystemSound(typer_soundid) : AudioServicesPlaySystemSound(0)
            }
        }
    }
    
}
